<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 搜索 -->
            <el-header class="page-header">
                <el-space :size="10">
                    <el-input v-model.trim="lookupData.title" placeholder="请输入优惠劵名称" clearable />
                    <el-select v-model="lookupData.type" placeholder="请选择优惠劵类型" clearable>
                        <el-option v-for="(item,index) in options.couponTypeMap" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select v-model="lookupData.status" placeholder="请选择优惠劵状态" clearable>
                        <el-option v-for="(item,index) in options.couponStatusMap" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-button type="primary" :icon="Search" @click="handlerLookup">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="handlerAddCoupon">添加</el-button>
                    <el-button type="primary" :icon="Download" @click="handlerExport">当前页导出</el-button>
                </el-space>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table style="width: 100%" :data="tableData" border id="table">
                        <el-table-column prop="id" label="优惠劵ID" align="center" sortable />
                        <el-table-column prop="title" label="优惠劵名称" align="center" />
                        <el-table-column label="优惠劵类型" align="center">
                            <template #default="scope">
                                <span>{{scope.row.type==1?'满减券':'立减券'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="介绍" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.description">
                                    {{scope.row.description}}
                                </span>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="total" label="优惠劵数量" align="center" />
                        <el-table-column prop="surplus" label="剩余数量" align="center" />
                        <el-table-column prop="limit" label="每人限额" align="center" />
                        <el-table-column label="满减金额" align="center">
                            <template #default="scope">
                                <span>减免{{scope.row.discount}}元</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="最低消费" align="center">
                            <template #default="scope">
                                <span>满{{scope.row.min}}元可用</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="scope">
                                <el-tag v-if="scope.row.status==1" :type="scope.row.gmtEnd < +new Date?'danger':''">
                                    {{scope.row.gmtEnd < +new Date?'已过期':'正常'}} </el-tag>
                                        <el-tag v-if="scope.row.status==0"
                                            :type="scope.row.gmtEnd < +new Date?'danger':'info'">
                                            {{scope.row.gmtEnd < +new Date?'已过期':'下架'}} </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="使用类目名称" align="center">
                            <template #default="scope">
                                <el-tag>{{scope.row.categoryTitle?scope.row.categoryTitle:'全部类目'}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryId" label="使用类目ID" align="center" />
                        <el-table-column prop="days" label="领券相对天数" align="center" />
                        <el-table-column label="领券开始时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtStart">
                                    {{new Date(scope.row.gmtStart).friendlyTime(3)}}
                                </span>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="领券结束时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtEnd">
                                    {{new Date(scope.row.gmtEnd).friendlyTime(3)}}
                                </span>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="260px">
                            <template #default="scope">
                                <el-button v-if="+new Date>scope.row.gmtEnd" type="primary">
                                    <span>已过期</span>
                                </el-button>
                                <el-button v-else-if="scope.row.status!=0"
                                    :type="scope.row.status==0?'primary':'danger'"
                                    @click="handlerFrozenCoupon(scope.row)">
                                    <span>{{scope.row.status==0?'正常':'冻结'}}</span>
                                </el-button>
                                <el-button v-else :type="scope.row.status==0?'primary':'danger'"
                                    @click="handlerFrozenCoupon(scope.row)">
                                    <span>{{scope.row.status==0?'激活':'下架'}}</span>
                                </el-button>
                                <el-button type="info" @click="handlerSeeCoupon(scope.row)">查看</el-button>
                                <el-button type="danger" @click="handlerDeleteCoupon(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页组件 -->
                <div class="page-pagination">
                    <Pagination v-bind="couponPagination" @handle-pagination="emitEntProps"/>
                </div>
                <!-- 回到顶部组件 -->
                <el-backtop :right="100" :bottom="100" target=".el-main" ref="refBacktop" />
                <!-- 添加表单对话框 -->
                <el-dialog v-model="dialogFormVisible" :title="refTitle" destroy-on-close>
                    <el-form ref="ruleFormRef" :model="dialogForm" status-icon :rules="rules" label-width="120px"
                        label-position="left" :disabled="refTitle=='编辑'">
                        <el-form-item label="优惠劵名称" prop="title" class="is-required">
                            <el-input v-model.trim="dialogForm.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="优惠劵类型" prop="type" class="is-required">
                            <el-select v-model="dialogForm.type" placeholder="请选择">
                                <el-option
                                    v-for="(item,index) in options.couponTypeMap.slice(0,options.couponTypeMap.length-1)"
                                    :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="介绍">
                            <el-input v-model.trim="dialogForm.description" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="优惠劵数量" prop="total" class="is-required">
                            <el-input v-model.trim="dialogForm.total" placeholder="请输入">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="每人限领" prop="limit" class="is-required">
                            <el-input v-model.trim="dialogForm.limit" placeholder="请输入">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠金额" prop="discount" class="is-required">
                            <el-input v-model.trim="dialogForm.discount" placeholder="请输入">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="最低消费" prop="min" class="is-required">
                            <el-input v-model.trim="dialogForm.min" placeholder="请输入">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠劵状态" prop="status" class="is-required">
                            <el-select v-model="dialogForm.status" placeholder="请选择">
                                <el-option
                                    v-for="(item,index) in options.couponStatusMap.slice(0,options.couponStatusMap.length-2)"
                                    :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="有效期">
                            <el-radio-group v-model="radioTime" style="margin-bottom: 20px;width:100%">
                                <el-radio-button label=0 >领券相对天数</el-radio-button>
                                <el-radio-button label=1 >指定相对天数</el-radio-button>
                            </el-radio-group>
                            <template v-if="radioTime == 0">
                                <el-input v-model.trim="dialogForm.days">
                                    <template #append>天</template>
                                </el-input>
                            </template>
                            <template v-else>
                                <el-col :span="10">
                                    <el-date-picker v-model="dialogForm.gmtStart" value-format="x" type="datetime" placeholder="选择开始日期"
                                        style="width: 100%" />
                                </el-col>
                                <el-col :span="4" style="text-align: center;">
                                    <span>至</span>
                                </el-col>
                                <el-col :span="10">
                                    <el-date-picker v-model="dialogForm.gmtEnd" value-format="x" type="datetime" placeholder="选择结束日期"
                                        style="width: 100%" />
                                </el-col>
                            </template>
                        </el-form-item>
                        <el-form-item label="商品限制范围">
                            <el-radio-group v-model="radioType" style="width:100%">
                                <el-radio-button label = 0 >全场通用</el-radio-button>
                                <el-radio-button label = 1 >指定分类</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="radioType == 1" label="优惠类目">
                            <el-cascader :options="cascaderList" :props="cascaderProps" v-model="dialogForm.categoryId" clearable placeholder="优惠类目" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="refTitle!='编辑'">确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ClassPagination } from '#/index';
import { reactive, ref, nextTick } from "vue";
import { Search, Plus, Download } from '@element-plus/icons-vue';
import { post } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from 'element-plus'
import * as XLSX from "xlsx";



const ruleFormRef = ref<FormInstance>()
const refBacktop = ref()
/**
 * 头部搜索数据
 * title:'',   //优惠卷标题
 * type:'',    //优惠卷类型
 * status:''   //优惠卷状态
 */
const lookupData = reactive({
    title: '',   //优惠卷标题
    type: '',    //优惠卷类型
    status: ''   //优惠卷状态
})
const refTitle = ref<string>("创建")
/**
 * 获取到的表格数据
 */
const tableData: TypeCoupon[] = reactive([])
/**
 * 下拉列表数据
 */
const options = reactive({
    couponStatusMap: [{ value: '0', label: '下架', }, { value: '1', label: '正常', }, { value: '-1', label: '已过期', }, { value: null, label: '全部', }],
    couponTypeMap: [{ value: '1', label: '满减券', }, { value: '2', label: '立减券', }, { value: null, label: '全部', }],
})
/**
 * 分页数据
 */
const couponPagination = reactive(new ClassPagination())
const dialogFormVisible = ref(false)
/**
 * 定义添加对话框数据
 * title: '',      //优惠卷标题
 * type: '',       //优惠卷类别，如满减
 * description: '',//优惠卷描述
 * total: '',      //优惠卷总数
 * limit: '',      //用户限制领取
 * discount: '',   //优惠价格
 * min: '',        //满足优惠的最低价格
 * status: '',     //优惠卷状态
 * categoryId: '', //优惠类别
 * days: '',       //优惠时长
 * gmtStart: '',   //	优惠开始时间
 * gmtEnd: '',     //优惠结束时间
 */
const dialogForm = reactive({
    title: '',      //优惠卷标题
    type: undefined,       //优惠卷类别，如满减
    description: '',//优惠卷描述
    total: 0,      //优惠卷总数
    limit: 0,      //用户限制领取
    discount: 0,   //优惠价格
    min: 0,        //满足优惠的最低价格
    status: undefined,     //优惠卷状态
    categoryId: 0, //优惠类别
    days: '',       //优惠时长天数
    gmtStart: '',   //优惠开始时间
    gmtEnd: '',     //优惠结束时间

})
/**
 * 获取对话框数据的空值
 */
const dialogFormNull = { ...dialogForm }
const radioTime = ref(0)
const radioType = ref(0)
/**
 * 存储类目树数据
 */
const cascaderList: Array<object> = reactive([])
/**
 * 存储类目树数据，规定子节点数据
 */
const cascaderProps = reactive({
    emitPath: false,//返回数字类型数据，true返回数组类型数据
    checkStrictly: true,
    children: 'childrenList',
    value: 'id',
    label: 'title',
})



// 验证函数
// 优惠券数量
function validateTotal(rule: Object, value: number, callback: Function) {
    let val = value + ''
    let title = /^[1-9]\d*\.?\d*$/
    if (!title.test(val)) {
        callback(new Error("请选择输入优惠券数量,不能为0"))
    }else if (dialogForm.limit>value) {
        callback(new Error("总数不能小于每人限领"))
    } else {
        callback()
    }
}
// 每人限领
function validateLimit(rule: Object, value: number, callback: Function) {
    let val = value + ''
    let limit = /^[1-9]\d*\.?\d*$/
    if (!limit.test(val)) {
        callback(new Error("请选择输入每人限领,不能为0"))
    } else if (dialogForm.limit>dialogForm.total) {
        callback(new Error("每人限领不能大于总数"))
    } else {
        callback()
    }
}
// 优惠金额
function validateDiscount(rule: Object, value: number, callback: Function) {
    let val = value + ''
    let discount = /^[1-9]\d*\.?\d*$/
    if (!discount.test(val)) {
        callback(new Error("请选择输入优惠金额,不能为0"))
    } else if (dialogForm.discount>dialogForm.min) {
        callback(new Error("优惠金额不能大于最低消费"))
    } else {
        callback()
    }
}
// 最低消费
function validateMin(rule: Object, value: number, callback: Function) {
    let val = value + ''
    let min = /^[1-9]\d*\.?\d*$/
    if (!min.test(val)) {
        callback(new Error("请选择输入最低消费,不能为0"))
    } else if (dialogForm.min<dialogForm.discount) {
        callback(new Error("最低消费不能小于优惠金额"))
    } else {
        callback()
    }
}
//验证规则
const rules = reactive({
    title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' },],
    total: [{ validator: validateTotal, trigger: 'blur' }],
    limit: [{ validator: validateLimit, trigger: 'blur' }],
    discount: [{ validator: validateDiscount, trigger: 'blur' }],
    min: [{ validator: validateMin, trigger: 'blur' }],
    status: [{ required: true, message: '请选择优惠券状态', trigger: 'change' },],
})
/**
 * 确定添加优惠劵
 */
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (dialogForm.gmtStart>dialogForm.gmtEnd) {
                ElMessage.warning('结束时间不能大于开始时间,请重新选择！')
                dialogForm.gmtStart = ''
                dialogForm.gmtEnd = ''
            }else{
                let data = {
                _gp: 'admin.coupon',
                _mt: 'create',
                ...dialogForm
            }
            post(data).then((res) => {
                if (200 === res.errno) {
                    getInitCoupon()
                    dialogFormVisible.value = false
                    ElMessage.success("添加成功")
                } else {
                    ElMessage.error(res.errmsg)
                }
            })
            }
        } else {
            return false
        }
    })
}
/**
 * 获取表格数据去请求
 */
function getInitCoupon() {
    let data = {
        _gp: 'admin.coupon',
        _mt: 'list',
        title: lookupData.title,
        type: lookupData.type,
        status: lookupData.status,
        pageNo: couponPagination.page,
        limit: couponPagination.limit,
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            console.log(res);
            let { items, total } = res.data
            tableData.length = 0
            tableData.push(...items)
            couponPagination.total = total
        } else {
            tableData.length = 0
            ElMessage.warning(res.errmsg)
        }
    })
}
/**
 * 查找数据
 */
function handlerLookup() {
    couponPagination.page = 1
    getInitCoupon()
}
/**
 * 获取类目树数据
 */
function gitCategory() {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            cascaderList.length = 0
            cascaderList.push(...res.data)
            console.log(cascaderList);
        }
    })
}
// 如果已经请求了那么就不用重复请求
if(cascaderList.length<=0){
    gitCategory()
}
/**
 * 添加优惠券
 */
function handlerAddCoupon() {
    Object.assign(dialogForm, dialogFormNull)
    radioTime.value = 0
    radioType.value = 0
    refTitle.value = "添加"
    dialogFormVisible.value = true
}
/**
 * 导出当前页数据
 */
function handlerExport() {
    let workbook = XLSX.utils.table_to_book(document.getElementById("table")); //需要在table上定义一个id
    try {
        XLSX.writeFile(workbook, "表格信息.xlsx");
        ElMessage({
            type: "success",
            message: "导出成功!",
        });
    } catch (e) {
        ElMessage.error("导出失败,失败信息:!");
    }
}
/**
 * 删除优惠劵
 */
function handlerDeleteCoupon(id: number) {
    ElMessageBox.confirm(
        '确认是否删除?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
    ).then(() => {
        post({
            _gp: 'admin.coupon',
            _mt: 'delete',
            id
        }).then(res => {
            if (200 === res.errno) {
                getInitCoupon()
                ElMessage.success("删除成功")
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }).catch(() => {
        ElMessage.warning("已取消删除")
    })

}
/**
 * 激活、冻结、数据
 * @param row   表格数据
 */
function handlerFrozenCoupon(row: TypeCoupon) {
    let data = {
        _gp: 'admin.coupon',
        _mt: 'updateCouponStatus',
        id: row.id,
        status: row.status == 0 ? 1 : 0
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            getInitCoupon()
            ElMessage.success("操作成功")
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}
/**
 * 查看优惠劵
 */
function handlerSeeCoupon(row: TypeCoupon) {
    refTitle.value = "编辑"
    dialogFormVisible.value = true
    Object.assign(dialogForm, row)
    radioTime.value = row.days ? 0 : 1
    radioType.value = row.categoryId ? 1 : 0
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
 function emitEntProps(val: { page: number, limit: number }) {
    let paging = couponPagination
    paging.page = val.page
    paging.limit = val.limit
    getInitCoupon()
}

// 页面渲染第一次调用
getInitCoupon()
</script>

<style lang="less" scoped>
.el-form {
    padding: 0px 30px;
}
</style>